<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\api\controller\GeTui;
use app\BaseController;
use app\model\Order as OrderModel;
use app\model\OrderDetail;
use app\model\Sale as SaleModel;
use app\model\Users;
use PHPMailer\PHPMailer\PHPMailer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;


class Order extends BaseController
{
    public function index()
    {
        $order_no=request()->param('order_no');
        $order_type=request()->param('order_type');
        $status=request()->param('status');
        $time=request()->param('time');

        $data=OrderModel::when($order_no,function ($query) use($order_no){
            $query->where('order_no',$order_no);
        })->when($time,function ($query) use($time){
            $start=strtotime(explode(',',$time)[0]);
            $end=strtotime(explode(',',$time)[1]);
            $query->whereBetween('created_at',[$start,$end]);
        })->when($order_type,function ($query) use($order_type){
            $query->where('order_type',$order_type);
        })->when($status,function($query) use($status){
            if(in_array($status,[10,20,50])){
                $query->where('status',$status);
            }})->with('detail.product')
        ->order('id','desc')->paginate(10);
        $start=strtotime(date('Y-m-d'));
        $end=strtotime(date('Y-m-d 23:59:59'));
        $money['today']=OrderModel::where('status','>',10)->whereBetween('created_at',[$start,$end])->sum('pay_price');
        $money['totalprices']=OrderModel::where('status','>',10)->sum('pay_price');
        $money['month']=OrderModel::where('status','>',10)->whereMonth('created_at')->sum('pay_price');
        return $this->success(compact('data','money'));
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function calendar()
    {
        $status=request()->param('status');

        $data=OrderModel::when($status,function($query)use($status){
            if(in_array($status,[1,2,3])){
                $query->where('order_type',$status)->order('status','desc');
            }
        })->order('created_at','desc')->select();
        $todayStart = strtotime(date('Y-m-d')); // 获取今天的起始时间戳
        $todayEnd = strtotime(date('Y-m-d 23:59:59')); // 获取今天的结束时间戳
        $money['today'] = OrderModel::whereBetween('created_at', [$todayStart, $todayEnd])->sum('pay_price');
        $money['total']=OrderModel::sum('pay_price');
        return  $this->success(compact('data','money'));

    }

    public function update($id)
    {
        $time=request()->param('time');

        $time=date('Y-m-d H:i:s',strtotime($time));
        $order=OrderModel::where('id',$id)->find();
        OrderModel::where('id',$id)->update(['time'=>$time]);
        $this->mail($order['address'][0]['email'],'訂單','您的預約時間改為'.$time);
        return $this->success();
    }

    public function create()
    {
      $data=request()->param();

      foreach ($data as $item){
         $model= OrderModel::create([
              'order_no'=>$this->createOrderNo1(),
              'status'=>OrderModel::STATUS_SUCCESS,
              'users_id'=>$item['users_id'],
              'pay_price'=>$item['total'],
              'pay_mode'=>3,
              'order_type'=>$item['type'],
          ]);

        OrderDetail::create([
            'order_id'=>$model->id,
            'product_id'=>$item['id'],
            'num'=>1,
            'price'=>$item['price']
        ]);
          Users::where('id',$item['users_id'])->inc('consume_num')->update();
          Users::where('id',$item['users_id'])->inc('consume',$item['total'])->update();
          \app\model\Product::where('id',$item['id'])->dec('num')->update();
          \app\model\Product::where('id',$item['id'])->inc('sale_money',$item['total'])->update();
          \app\model\Product::where('id',$item['id'])->inc('sales')->update();
      }
    return $this->success();
    }

    public function over()
    {
        $id=request()->param('id');

        $order=OrderModel::where('id',$id)->find();
        $price=OrderDetail::where('order_id',$id)->select()->toArray();
        $sum= \app\model\Product::where('id','in',array_column($price,'product_id'))->sum('price');
        OrderModel::where('id',$id)->update(['status'=>OrderModel::STATUS_SUCCESS,'pay_price'=>$sum]);
        $user=Users::where('id',$order['users_id'])->find();

        $this->mail($order['address'][0]['email'],'訂單','您的訂單狀態已更改为確認');
        $tui= new GeTui();
        $tui->pushMessageToSingle($user['client_id'],'您的訂單狀態已更改为確認',$user['type']);

        return $this->success();
    }

  public function mail($email,$title,$content)
    {

        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = "utf-8";                     //utf-8;
        $mail->Encoding = "base64";
        $mail->Host = env('MAIL.MAIL_HOST');
        $mail->SMTPAuth = true;
        $mail->Username = env('MAIL.MAIL_USERNAME');
        $mail->Password = env('MAIL.MAIL_PASSWORD');
        $mail->SMTPSecure = env('MAIL.MAIL_ENCRYPTION');
        $mail->Port = env('MAIL.MAIL_PORT');
        $mail->setFrom(env('MAIL.MAIL_FROM_ADDRESS'), env('MAIL.MAIL_FROM_NAME'));
        $mail->addAddress(trim($email));
        $mail->Subject = $title;
        $mail->Body = $content;
        $mail->send();

    }


    public function bill()
    {

        $id = request()->param('id');
        $data = OrderModel::where('id', $id)->with('detail.product')->find();

        if ($data->status != 50) {
            $str = 'Invoice' . config('params.company.name');
        } else {
            $str = 'Receipt' . config('params.company.name');
        }

        $type = [1 => 'Paypal', 2 => '錢包', 3 => '線下',4=>'Stripe'];
        $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

        // 设置文档信息
        $pdf->SetCreator('My Application');
        $pdf->SetAuthor('John Doe');
        $pdf->SetTitle('My PDF');
        $pdf->SetSubject('Test');

        // 设置页眉数据

        $pdf->SetHeaderData('../../../../../public/logo.png', 10, $str, '');

        // 设置页眉和页脚字体
        $pdf->setHeaderFont(['stsongstdlight', '', '10']);

        // 添加页面
        $pdf->AddPage();

        // 写入内容
        if ($data->pay_mode == 3) {
            $mobile = '線下訂單';
            $name = '線下訂單';
        } else {
            $mobile = $data->address['mobile'];
            $name = $data->address['name'];
        }

        $pdf->SetFont('stsongstdlight', '', 12);
        $pdf->Write(5, "訂單號：$data->order_no");
        $pdf->Ln(); // 换行
        $pdf->Write(5, "實際支付：$data->pay_price");
        $pdf->Ln(); // 换行
        $pdf->Write(5, "電話：$mobile");
        $pdf->Ln(); // 换行
        $pdf->Write(5, "姓名：$name");
        $pdf->Ln(); // 换行
        $pdf->Write(5, "下單時間：$data->created_at");
        $pdf->Ln(); // 换行
        $pdf->Write(5, "支付方式：{$type[$data->pay_mode]}");
        $pdf->Ln(); // 换行

        // 表格标题行
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->Cell(100, 10, '產品名稱', 1, 0, 'C');
        $pdf->Cell(30, 10, '數量', 1, 0, 'C');
        $pdf->Cell(30, 10, '產品價格', 1, 0, 'C');
        $pdf->Ln(); // 换行

        // 表格内容
        $pdf->SetFont('stsongstdlight', '', 12);
        foreach ($data->detail as $detail) {
            $product = $detail->product;
            $pdf->Cell(100, 10, $product->name, 1, 0, 'L');
            $pdf->Cell(30, 10, $detail->num, 1, 0, 'C');
            $pdf->Cell(30, 10, $detail->price, 1, 0, 'R');
            $pdf->Ln(); // 换行
        }

        $pdf->Ln(); // 换行
        $pdf->Write(5, '如果您有任何問題，請使用下列聯絡資訊：於 APP/ Facebook 專頁 聯絡我們！感謝您的惠顧！');
        $pdf->Ln(); // 换行
        $pdf->Ln(); // 换行

        // 输出地址信息
        $address = \app\model\Store::where('id', '>', 0)->find();
        $pdf->Write(5, $address['address']);
        $pdf->Ln(); // 换行

        // 输出日期
        $pdf->Write(5, 'DATE：' . date('Y-m-d H:i:s'));

//        $name = public_path() . '/pdf';
//        $fileName = time() . '.pdf';
//        $pdf->Output($name . $fileName, 'F');
//
//        return $this->success('https://'.request()->host().'/pdf'.$fileName);

        // 输出PDF到文件
        $name = public_path().'/uploads' . '/pdf';

        $fileName = $str.'.pdf';
        $pdf->Output($name . $fileName, 'F');

        return $this->success(ossUpload($name . $fileName));
    }

    public function delete($id)
    {
        OrderModel::where('id',$id)->delete();
        OrderDetail::where('order_id',$id)->delete();
        return $this->success();
    }


    private function createOrderNo1(){
        $date = date('Ymd');
        $rand = mt_rand(1000, 9999); // 生成 4 位随机数
        $chars = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
        shuffle($chars);
        $str = implode('', array_slice($chars, 0, 4)); // 选择 8 个字符生成随机字符串
        return $date . $rand . $str; // 连接日期、随机数和随机字符串
    }

}
